// 引入所需的 Cesium 模块
import * as Cesium from 'cesium';
import "cesium/Build/Cesium/Widgets/widgets.css";
// 假设您已经有一个 Cesium.Viewer 实例名为 viewer
const viewer = new Cesium.Viewer('cesiumContainer', {
    terrainProvider: new Cesium.createWorldTerrainAsync(),
    baseLayerPicker: true,
    geocoder: true,
    homeButton: true,
    sceneModePicker: true,
    navigationHelpButton: true,
    animation: true,
    timeline: true,
    fullscreenButton: true
});

// 启用地形深度测试
viewer.scene.globe.enableLighting = true;
viewer.scene.globe.depthTestAgainstTerrain = true;
// 定义正方形的顶点坐标（这里假设在地球表面上）
const positions = Cesium.Cartesian3.fromDegreesArray([-75.0, 40.0, -75.0, 40.1, -74.9, 40.1, -74.9, 40.0]);

// 创建几何体实例
const geometry = new Cesium.GeometryInstance({
    geometry: new Cesium.PolygonGeometry({
        polygonHierarchy: new Cesium.PolygonHierarchy(positions),
        vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT
    })
});

// 创建自定义着色器材质
const material = new Cesium.Material({
    fabric: {
        type: 'CustomShader',
        uniforms: {
            image: new Cesium.TextureUniform({
                url: 'path/to/your/initial/image.jpg'
            }),
            time: 0
        },
        source: `
      uniform sampler2D image;
      uniform float time;
      
      czm_material czm_getMaterial(czm_materialInput materialInput) {
        czm_material material = czm_getDefaultMaterial(materialInput);
        
        vec2 st = materialInput.st;
        
        // 添加一些简单的动画效果
        st.s += sin(st.t * 10.0 + time) * 0.01;
        
        vec4 textureColor = texture2D(image, st);
        
        material.diffuse = textureColor.rgb;
        material.alpha = textureColor.a;
        
        return material;
      }
    `
    }
});

// 创建外观
const appearance = new Cesium.EllipsoidSurfaceAppearance({
    material: material,
    fragmentShaderSource: `
    varying vec3 v_positionMC;
    varying vec3 v_positionEC;
    varying vec2 v_st;

    void main() {
      czm_materialInput materialInput;
      materialInput.s = v_st.s;
      materialInput.st = v_st;
      materialInput.str = vec3(v_st, 0.0);
      materialInput.normalEC = normalize(czm_normal3D * czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0)));
      materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, materialInput.normalEC);
      materialInput.positionToEyeEC = -v_positionEC;

      czm_material material = czm_getMaterial(materialInput);

      gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);
    }
  `
});

// 创建 Primitive
const primitive = new Cesium.Primitive({
    geometryInstances: geometry,
    appearance: appearance,
    asynchronous: false
});

// 将 Primitive 添加到场景中
viewer.scene.primitives.add(primitive);

// 更新时间 uniform 以创建动画效果
viewer.scene.preUpdate.addEventListener(function(scene, time) {
    material.uniforms.time = Cesium.JulianDate.secondsDifference(time, Cesium.JulianDate.fromDate(new Date(2020, 0, 1)));
});

// 将视图定位到正方形
viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(-75.0, 40.05, 100000)
});

// 函数：更新材质的图片
function updateImage(newImageUrl) {
    material.uniforms.image = new Cesium.TextureUniform({
        url: newImageUrl
    });
}

// 示例：5秒后更换图片
setTimeout(() => {
    updateImage('path/to/your/new/image.jpg');
}, 5000);